package com.example.kingdee.KingdeeCreate.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.example.kingdee.KingdeeCreate.CreateBill;
import com.example.kingdee.KingdeeCreate.dto.CreateInDto;
import com.example.kingdee.common.StringUtils;
import com.example.kingdee.common.constant.YiTiConstant;
import com.example.kingdee.entity.ItemsItem;
import com.example.kingdee.entity.JstSalOut;
import com.example.kingdee.exception.ProcedureException;
import com.example.kingdee.kingdeeBridge.common.RequestResult;
import com.example.kingdee.mapper.TBxStMapper;
import com.example.kingdee.sqlTool.SqlTool;
import com.example.kingdee.sqlTool.common.DataObject;
import com.example.kingdee.sqlTool.sqltoolEnum.FormIdEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 创建销售订单
 */
@Service
public class CreateSalOutBillImpl implements CreateBill {

    @Autowired
    private SqlTool sqlTool;

    @Autowired
    private TBxStMapper tBxStMapper;

    @Override
    public void preposition(CreateInDto createInDto) {

    }

    /*
     *
     * @param createInDto
     * reserved1为调入仓库编码，reserved2为调入仓位编码
     * @return
     */
    @Override
    public RequestResult createSrcBill(CreateInDto createInDto) {
        Object shopName = createInDto.getReserved1();//店铺名称
        //查询组织编码
        String orgNumber = tBxStMapper.getShopOrgNumber(shopName);
        if (StringUtils.isEmpty(orgNumber)){
            return RequestResult.ofError("无法查询到对应组织，请维护正确的销售组织");
        }
        //单据类型 FBillTypeID, 002-电商销售订单， XSDD01_SYS-标准销售订单，
        Map<String, Object> fBillTypeID = new HashMap<>();
        fBillTypeID.put("FNUMBER", "XSCKD01_SYS");
        //设定要货日期为当前日期加15天
        Date date = new Date();
        DateTime newDate = DateUtil.offsetDay(date, 10);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String deliveryDate = format.format(newDate);
        //销售组织 FSaleOrgId
        Map<String, Object> saleOrgId = new HashMap<>();
        saleOrgId.put("FNumber", orgNumber);
        //客户 FCustId
        Map<String, Object> customerId = new HashMap<>();
        customerId.put("FNumber", YiTiConstant.SAL_CUSTOMER_NUMBER);

        //财务信息  FSaleOrderFinance
        Map<String,Object> saleOrderFinance = new LinkedHashMap<>();
        //结算币别  FSettleCurrId
        Map<String, Object> settleCurrId = new HashMap<>();
        settleCurrId.put("FNumber", "PRE001");
        saleOrderFinance.put("FSettleOrgID", saleOrgId);
        saleOrderFinance.put("FSettleCurrId", settleCurrId);
        //订单明细  FSaleOrderEntry
        List<Map<String, Object>> saleOrderInfoList = new ArrayList<>();
        List<JstSalOut.ItemsBean> salOutItems = createInDto.getSalOutItems();
        for (JstSalOut.ItemsBean item : salOutItems) {
            Map<String,Object> saleOrderEntry = new LinkedHashMap<>();
            Integer row = tBxStMapper.itemIsExist(item.getSkuId(), orgNumber);
            if (row == 0){
                saleOrderEntry.put("F_WMVJ_TEXT_TZK", item.getSkuId());//聚水潭物料编码
                item.setSkuId("9999");
            }
            String unitNumber = tBxStMapper.getUnitNumber(item.getSkuId());
            Map<String, Object> materialId = new HashMap<>(); //物料编码 必填
            materialId.put("FNumber", item.getSkuId());
            Map<String, Object> materialUnit = new HashMap<>(); //销售单位 必填
            materialUnit.put("FNumber", unitNumber);
            HashMap<String, Object> stockId = new HashMap<>();
            stockId.put("fnumber", "CK001");

            saleOrderEntry.put("FMaterialId", materialId);//物料编码 必填
            saleOrderEntry.put("FUnitID", materialUnit);//库存单位 必填
            saleOrderEntry.put("FMustQty", item.getQty());//应发数量 (必填项)
            saleOrderEntry.put("FRealQty", item.getQty());//实发数量 (必填项)
            saleOrderEntry.put("FOwnerTypeId", "BD_OwnerOrg");//调入货主类型
            saleOrderEntry.put("FOwnerID", saleOrgId);//货主
            saleOrderEntry.put("FStockID", stockId);//仓库
            if (item.getQty() != 0.0){
                saleOrderInfoList.add(saleOrderEntry);
            }
        }
        //添加销售出库单
        DataObject saleOrder = new DataObject(FormIdEnum.salOutStock);
        //创建日期
        saleOrder.setAttribute("FSaleOrgId", saleOrgId);//销售组织 必填
        saleOrder.setAttribute("FBillTypeID", fBillTypeID);//单据类型 必填 固定值
        saleOrder.setAttribute("FDate", createInDto.getReserved2());//日期 (必填项)
        saleOrder.setAttribute("FStockOrgId", saleOrgId);//发货组织 (必填项)
        saleOrder.setAttribute("FCustomerID", customerId);//客户 (必填项)
        saleOrder.setAttribute("FNote", createInDto.getReserved3());//备注
        saleOrder.setAttribute("SubHeadEntity", saleOrderFinance);//财务信息
        saleOrder.setAttribute("FEntity", saleOrderInfoList);//订单明细

        try {
            Map<String, Object> result = sqlTool.editForDataObject(saleOrder);
            if (result.get("code").toString().equals("200")){
                return RequestResult.ofSuccess(result);
            }else {
                return RequestResult.ofError(result.get("msg").toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ProcedureException("无法调用云星空接口");
        }
    }

    @Override
    public void auditTargetBill(String billNo) {
        //提交审核
        sqlTool.auditBill(billNo, FormIdEnum.salOutStock);
    }

    @Override
    public void postPosition(RequestResult srcBill, CreateInDto createInDto) {

    }

    @Override
    public void deleteTargetBill(String fid) {
        sqlTool.deleteBill(fid, FormIdEnum.salOutStock);
    }
}
